//
//  PostDetailVC.m
//  sensen_ios
//
//  Created by pro on 16/3/2.
//  Copyright © 2016年 pro. All rights reserved.
//  论坛_详情删除贴子

#import "PostDetailVC.h"

//#import "ForumSectionVC.h"
#import "ReplyDetailVC.h"
// 单元格
#import "PostDetailCell.h" // 帖子详情
#import "CommentCell.h" // 评论内容
#import "EmptyCell.h"

// 视图
#import "FaceView.h" // 表情

#import "ZKTextImgReplaceHandle.h"
#import "PostDetailImgsView.h"
/*
 宏定义
 */
#define kTfTag 10 // 输入框的tag
@interface PostDetailVC () <UITableViewDataSource, UITableViewDelegate, FaceViewDelegate,favourButtonDelegate,replyButtonDelegate,UICollectionViewDataSource, UICollectionViewDelegate,UIActionSheetDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate,UMSocialUIDelegate>
{
    UIView *_maskView; // 罩着视图
    UIView *_sendView; // 发送评论视图
    UITableView *_tableView; // 表视图
    UITextField *_tf; //评论框
    FaceView *_faceView; // 表情
    UICollectionView *_collectionView; // 放图片的滑动视图
    NSMutableArray *_imgAry; // 图片数组
    UILabel *_notesLabel; // 标注视图，注释当前已经有几张图片，并告知还有几张可选
    NSMutableArray *_imIdAry;
    UIView *_contentBasalView;// 添加图片视图
    UIButton *_deButton; //删除按钮
    UIButton *_dingButton; //置顶按钮
    UIButton *_digestButton;//加精按钮
    UIButton *_coButton;//收藏按钮
    UIImageView *_imgView; // 表情按钮
    UIButton *_reSendButton;//回复按钮
    UIButton *_sendButton; //发送按钮
    NSString *_pid;
    NSInteger _page;
    NSInteger _islove;
    UIImage *_mainImage;
}

/*
 数据类
 */
@property (nonatomic, strong) NSMutableArray *commentsAry; // 评论数量
@property (nonatomic, strong) UIView *shareView; // 分享视图
@end

@implementation PostDetailVC

#pragma mark - 控制器视图方法
- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.title == nil) {
        self.title = @"话题";
    }
    self.view.backgroundColor = [UIColor whiteColor];
    [self createLeftBarButtonItemWithImagename:nil]; // 左侧返回按钮
    
    [self _createViews];
//    [self _initData];
    [self createRightBarButtonItems]; // 创建导航栏右侧按钮（收藏和分享）
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardDown)];
    [self.view addGestureRecognizer:tap];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self _initData];
    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main hideTabBar];
}
- (void)viewWillDisappear:(BOOL)animated {
    
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main showTabBar];
}

#pragma mark - 初始化数据
- (void)_initData {
    _page = 1;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(_getMoreData)];
    _tableView.footer = footer;
    [SVProgressHUD showWithStatus:@"请耐心等待..." maskType:SVProgressHUDMaskTypeBlack]; // 请求中
    self.view.userInteractionEnabled = NO;
    UserModel *user = [CommonCache getUserInfo];
    BOOL isLogin = FALSE;
    if (user != nil) {
        isLogin = TRUE;
    }
    __weak PostDetailVC * that = self;
    NSDictionary *params;
    if (_fid == nil) {
        params = @{@"tid":_tid,@"curpage":@"1",@"pagesize":@"5"};
    }else{
        params = @{@"tid":_tid,@"fid":_fid,@"curpage":@"1",@"pagesize":@"5"};
    }
    [BoyeHttpClient post:@"BY_ForumPost_query" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        if (![result[@"list"] isKindOfClass:[NSNull class]]) {
            NSString *count = result[@"count"];
            NSInteger nub = [count integerValue];
            NSArray *array = result[@"list"];
            NSDictionary *resultDic = array[0];
            PostModel *postModel = [[PostModel alloc] initContentWithDic:resultDic];
            _layout = [[PostCellFrameLayout alloc] init];
            _layout.cellType = ZKCellDetail;
            _layout.model = postModel;
            _fid = postModel.fid;
            NSMutableDictionary * params = [[NSMutableDictionary alloc]init];
            [params setObject:_tid forKey:@"tid"];
            if (isLogin) {
                [params setObject:user.uid forKey:@"uid"];
            }
            if (_commentsAry == nil) {
                _commentsAry = [[NSMutableArray alloc] init];
            } else {
                [_commentsAry removeAllObjects];
            }
            [that setComments:array];
            [that loadDetail];
            if (_commentsAry.count == (nub - 1)) {
                [_tableView.footer removeFromSuperview];
            }
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"1=====%@",error);
        self.view.userInteractionEnabled = YES;
        
        [SVProgressHUD showErrorWithStatus:@"加载失败" withDuration:1];
    }];
    
    
}

-(void) setComments :(NSArray * )array {
   
    for (NSInteger i = 0; i < array.count - 1; i++) {
        NSDictionary *resDic = array[i+1];
        CommentModel *commentModel = [[CommentModel alloc] initContentWithDic:resDic];
        CommentCellFrameLayout *commentLayout = [[CommentCellFrameLayout alloc] init];
        commentLayout.model = commentModel;
        if (i == 0) {
            commentLayout.model.nuber = [NSString stringWithFormat:@"沙发"];
        }else{
            commentLayout.model.nuber = [NSString stringWithFormat:@"第%li楼",i+2];
        }
        [_commentsAry addObject:commentLayout];
    }
    [_tableView reloadData];

}

-(void) loadDetail{
    UserModel *user = [CommonCache getUserInfo];
    BOOL isLogin = FALSE;
    if (user != nil) {
        isLogin = TRUE;
    }
    NSMutableDictionary * params = [[NSMutableDictionary alloc]init];
    [params setObject:_tid forKey:@"tid"];
    if (isLogin) {
        [params setObject:user.uid forKey:@"uid"];
    }
    
    [BoyeHttpClient post:@"BY_ForumThread_detail" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        PostModel *postModel = [[PostModel alloc] initContentWithDic:result];
        _layout.model.likes = postModel.likes;
        _layout.model.stick = postModel.stick;
        _isStick = [postModel.stick boolValue];
        _isLike = [postModel.favorite boolValue];
        _isDigest = [postModel.digest boolValue];
        _islove = [postModel.is_love boolValue];
        if (isLogin && _isLike) {
            [_coButton setImage:[UIImage imageNamed:@"论坛首页_详情页_收藏2"] forState:UIControlStateNormal];
        }
        [_tableView reloadData];
        [SVProgressHUD dismiss];
        if ([postModel.status integerValue] != 1) {
            [SVProgressHUD showOnlyStatus:@"该帖已经被删除" withDuration:1.5];
            [self.navigationController popViewControllerAnimated:YES];
        }
        self.view.userInteractionEnabled = YES;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        self.view.userInteractionEnabled = YES;
        [SVProgressHUD showErrorWithStatus:@"加载失败" withDuration:1];
    }];

}

- (void)_getMoreData {
    _page += 1;
    NSString *curpage = [NSString stringWithFormat:@"%li",(unsigned long)_page];
    NSDictionary *params;
    params = @{@"tid":_tid,@"curpage":curpage,@"pagesize":@"5"};
    [BoyeHttpClient post:@"BY_ForumPost_query" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        if (![result[@"list"] isKindOfClass:[NSNull class]]){
            NSString *count = result[@"count"];
            NSInteger nub = [count integerValue];
            NSArray *array = result[@"list"];
            for (NSInteger i = 0; i < array.count ; i++)  {
                NSDictionary *resDic = array[i];
                CommentModel *commentModel = [[CommentModel alloc] initContentWithDic:resDic];
                CommentCellFrameLayout *commentLayout = [[CommentCellFrameLayout alloc] init];
                commentLayout.model = commentModel;
                commentLayout.model.nuber = [NSString stringWithFormat:@"第%li楼",i-4+5*_page];
                [_commentsAry addObject:commentLayout];
            }
            [_tableView.footer endRefreshing];
            if (_commentsAry.count == (nub - 1)) {
                [_tableView.footer removeFromSuperview];
            }
        }
        [_tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"加载失败" withDuration:1];
    }];
}
#pragma mark - 创建视图
#pragma mark -- 创建导航栏视图 --
// 创建导航栏右侧按钮（收藏和分享）
- (void)createRightBarButtonItems {
    NSString *imgName;
    if (_isLike == YES) {
        imgName = @"论坛首页_详情页_收藏2";
    }else{
        imgName = @"论坛首页_详情页_收藏";
    }
    _coButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _coButton.frame = CGRectMake(0, 0, 20, 20);
    [_coButton setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
    [_coButton addTarget:self action:@selector(_naviRightAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 20, 20);
    [button setBackgroundImage:[UIImage imageNamed:@"论坛举报"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(_report:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(0, 0, 20, 20);
    [button1 setBackgroundImage:[UIImage imageNamed:@"论坛首页_详情页_分享"] forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(_share:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_coButton];
    UIBarButtonItem *barButtonItem2 = [[UIBarButtonItem alloc] initWithCustomView:button];
    UIBarButtonItem *barButtonItem3 = [[UIBarButtonItem alloc] initWithCustomView:button1];
    
    self.navigationItem.rightBarButtonItems =@[barButtonItem,barButtonItem2,barButtonItem3];
}

#pragma mark -- 创建子视图
- (void)_createViews {
    
    [self _initTableView]; // 表视图
    [self _createSendView]; // 发送评论
    [self _createFaceView]; // 表情
    [self _createCollectionView]; // 图片放置滑动视图

    [_NOTIFICATION_CENTER addObserver:self selector:@selector(faceViewFrameChange:) name:FaceViewFrameChange object:nil];
    
    [self _createMaskView]; // 遮罩视图
    
}
// 创建遮罩视图（键盘弹出时显示，键盘隐藏时也隐藏）
- (void)_createMaskView {
    
    _maskView = [[UIView alloc] initWithFrame:self.view.bounds];
    _maskView.backgroundColor = [UIColor clearColor];
    _maskView.hidden = YES;
    [self.view addSubview:_maskView];
    // 点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardDown)];
    [_maskView addGestureRecognizer:tap];
    // 左右滑手势
    UISwipeGestureRecognizer *swipeLR = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardDown)];
    swipeLR.direction = UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft;
    [_maskView addGestureRecognizer:swipeLR];
    // 上下滑手势
    UISwipeGestureRecognizer *swipeUD = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardDown)];
    swipeUD.direction = UISwipeGestureRecognizerDirectionDown | UISwipeGestureRecognizerDirectionUp;
    [_maskView addGestureRecognizer:swipeUD];

}

// 创建发送评论视图
- (void)_createSendView {
    
    CGFloat x, y, width, height;
    x = 0; y = 0;
    width = SCREEN_WIDTH;
    height = 49;
    _sendView = [[UIView alloc] init];
    _sendView.frame = CGRectMake(x, y, width, height);
    _sendView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    [self.view addSubview:_sendView];
    _sendView.bottom = SCREEN_HEIGHT - 64;
    
    // 拓展视图 +
    x = 5;
    width = 25;
    height = width;
    _imgView = [[UIImageView alloc] init];
    _imgView.userInteractionEnabled = YES;
    _imgView.frame = CGRectMake(x, y, width, height);
    _imgView.image = [UIImage imageNamed:@"论坛_发表帖子_表情"];
    [_sendView addSubview:_imgView];
    _imgView.center = CGPointMake(_imgView.center.x, _sendView.height / 2);
    UITapGestureRecognizer *faceTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_faceViewTap:)];
    [_imgView addGestureRecognizer:faceTap];
    
    // 发送按钮
    width = 60;
    height = _sendView.height;
    _sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _sendButton.frame = CGRectMake(SCREEN_WIDTH - width, 0, width, height);
    _sendButton.backgroundColor = [UIColor clearColor];
    [_sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [_sendButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    _sendButton.titleLabel.font = FONT(15);
    _sendButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [_sendButton addTarget:self action:@selector(_sendAction:) forControlEvents:UIControlEventTouchUpInside];
    [_sendView addSubview:_sendButton];
    _sendButton.right = SCREEN_WIDTH;
    
    _reSendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _reSendButton.frame = CGRectMake(SCREEN_WIDTH - width, 0, width, height);
    _reSendButton.backgroundColor = [UIColor clearColor];
    [_reSendButton setTitle:@"回复" forState:UIControlStateNormal];
    [_reSendButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    _reSendButton.titleLabel.font = FONT(15);
    _reSendButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [_reSendButton addTarget:self action:@selector(_replyAction:) forControlEvents:UIControlEventTouchUpInside];
    [_sendView addSubview:_reSendButton];
    _reSendButton.right = SCREEN_WIDTH;
    _reSendButton.hidden = YES;
    
    //添加图片
    x = _imgView.right + 5;
    width = 25;
    height = width;
    UIImageView *imgView1 = [[UIImageView alloc] init];
    imgView1.userInteractionEnabled = YES;
    imgView1.frame = CGRectMake(x, y, width, height);
    imgView1.image = [UIImage imageNamed:@"论坛_发表帖子_图片"];
    [_sendView addSubview:imgView1];
    imgView1.center = CGPointMake(imgView1.center.x, _sendView.height / 2);
    UITapGestureRecognizer *imageAdd = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_imageAdd:)];
    [imgView1 addGestureRecognizer:imageAdd];

    // 输入框
    x = imgView1.right + 5;
    width = _sendButton.left - x;
    height = 30;
    _tf = [[UITextField alloc] init];
    _tf.frame = CGRectMake(x, y, width, height);
    _tf.backgroundColor = [UIColor whiteColor];
    _tf.textColor = [UIColor darkGrayColor];
    _tf.clearButtonMode = UITextFieldViewModeWhileEditing;
    _tf.tag = kTfTag;
    NSString *string = @"  我也说一句";
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
    // 字体
    [attrString addAttribute:NSFontAttributeName
                       value:[UIFont systemFontOfSize:15]
                       range:[string rangeOfString:string]];
    _tf.attributedPlaceholder = attrString;
    [_sendView addSubview:_tf];
    _tf.center = CGPointMake(_tf.center.x, _sendView.height / 2);
}
// 创建表情视图
- (void)_createFaceView {
    
    _faceView = [[FaceView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 216)];
    _faceView.top = SCREEN_HEIGHT - 64;
    _faceView.delegate = self;
    [self.view addSubview:_faceView];
}
// 创建表视图
- (void)_initTableView {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
//    [_tableView setSeparatorColor:[UIColor blueColor]];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    // 注册单元格
    [_tableView registerClass:[PostDetailCell class] forCellReuseIdentifier:@"PostDetailCell"];
    [_tableView registerClass:[CommentCell class] forCellReuseIdentifier:@"CommentCell"];
    [_tableView registerClass:[EmptyCell class] forCellReuseIdentifier:@"EmptyCell"];
}

#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_commentsAry.count == 0) {
        return 2;
    }else{
        return 1 + _commentsAry.count;
    }
    
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    if (section == 0) {
//        return 1;
//    } else {
//        if (_commentsAry.count == 0) {
//            return 1;
//        }else{
//            return _commentsAry.count;
//        }
//    }
    return 1;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        PostDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PostDetailCell"];
        // 填充数据
        cell.layout = _layout;
        cell.delegate = self;
        if (_islove ) {
            [cell.favourButton setImage:[UIImage imageNamed:@"论坛_进入论坛_赞3"] forState:UIControlStateNormal];
        }
        PostDetailImgsView *postImgsView = (PostDetailImgsView *)([cell.contentView viewWithTag:3000]);
        if (postImgsView.imgAry.count == 0) {
            _mainImage = DEFAULT_IMAGE;
        }else{
            UIImageView *imgView =  (UIImageView *)[postImgsView viewWithTag:4000];
            _mainImage = imgView.image;
        }
        
       
        return cell;
    } else {
        if (_commentsAry.count == 0) {
            CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EmptyCell"];
            return cell;
        }else{
            CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentCell"];
            // 填充数据
            CommentCellFrameLayout *layout = _commentsAry[indexPath.section - 1];
            cell.layout = layout;
            cell.delegate = self;
            if ([_layout.model.author_id integerValue] == [layout.model.author_id integerValue]) {
                cell.louLabel.hidden = NO;
            }else{
                cell.louLabel.hidden = YES;
            }
            return cell;
        }
    }
    
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return _layout.cellRect.size.height;
    }
    else {
        if (_commentsAry.count == 0) {
            return 30;
        }else{
            CommentCellFrameLayout *layout = _commentsAry[indexPath.section - 1];
            return layout.cellRect.size.height;
        }
    }
    
}
// 设置组尾高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 50;
    } else {
        return 1;
    }
    
}
// 设置组头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *basalView = [[UIView alloc] init];
    // 帖子详情单元格
    if (section == 0) {
        // 头像
        UIImageView *iconImgView = [[UIImageView alloc] init];
        iconImgView.frame = CGRectMake(10, 10, 30, 30);
        NSURL * url;
        if (_layout.model.authorImage != nil) {
            url = [[NSURL alloc]initWithString:_layout.model.authorImage];
        }
        [iconImgView setImageWithURL: url placeholderImage:[UIImage imageNamed:@"defaultImage"]];
        
        iconImgView.layer.cornerRadius = 15;
        iconImgView.clipsToBounds = YES;
        [basalView addSubview:iconImgView];
        //删除按钮
        _deButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _deButton.frame = CGRectMake(SCREEN_WIDTH - 30, 15, 20, 20);
        [_deButton setImage:[UIImage imageNamed:@"论坛_详情删除帖子"] forState:UIControlStateNormal];
        [_deButton addTarget:self action:@selector(deletePost:) forControlEvents:UIControlEventTouchUpInside];
        [basalView addSubview:_deButton];
        _deButton.hidden = YES;
        //置顶按钮
        _dingButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _dingButton.frame = CGRectMake(SCREEN_WIDTH - 60, 15, 20, 20);
        [_dingButton setImage:[UIImage imageNamed:@"论坛_置顶按钮"] forState:UIControlStateNormal];
        [_dingButton addTarget:self action:@selector(dingPost:) forControlEvents:UIControlEventTouchUpInside];
        [basalView addSubview:_dingButton];
        _dingButton.hidden = YES;
        //加精按钮
        _digestButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _digestButton.frame = CGRectMake(SCREEN_WIDTH - 90, 15, 20, 20);
        [_digestButton setImage:[UIImage imageNamed:@"论坛首页-导航_精华帖2"] forState:UIControlStateNormal];
        [_digestButton addTarget:self action:@selector(_digest:) forControlEvents:UIControlEventTouchUpInside];
        [basalView addSubview:_digestButton];
        _digestButton.hidden = YES;

        // 昵称
        UILabel *nickLabel = [[UILabel alloc] init];
        CGFloat w = 180;
        if (SCREEN_WIDTH == 320) {
            w = 130;
        }
        CGFloat widthW = ([_layout.model.nickname getSizeOfString:18].width < w)? [_layout.model.nickname getSizeOfString:18].width : w;
        
        nickLabel.frame = CGRectMake(iconImgView.right + 10, iconImgView.top,widthW, 30);
        nickLabel.font = FONT(18);
        nickLabel.text = _layout.model.nickname;
        nickLabel.textColor = rgba(12, 91, 158, 1);
        if ([_layout.model.isAllowpost intValue] == 0 && _layout.model != nil) {
            nickLabel.text = @"禁言用户";
            nickLabel.textColor = [UIColor lightGrayColor];
            nickLabel.frame = CGRectMake(iconImgView.right + 10, iconImgView.top,[@"禁言用户" getSizeOfString:18].width, 30);
        }
        nickLabel.textAlignment = NSTextAlignmentLeft;
        [basalView addSubview:nickLabel];
        
        //楼主图片
//        UIImageView *image = [[UIImageView alloc] init];
//        image.image = [UIImage imageNamed:@"论坛首页-详情页-楼主"];
//        image.frame = CGRectMake(nickLabel.right + 5, iconImgView.top, 40, 20);
//        [basalView addSubview:image];
//        image.center = nickLabel.center;
//        image.left = nickLabel.right + 5;
        
        UILabel *label1 = [[UILabel alloc] init];
        label1.layer.cornerRadius = 3;
        label1.layer.masksToBounds = YES;
        label1.backgroundColor = rgba(12, 91, 158, 1);
        label1.text = @"楼主";
        label1.textColor = [UIColor whiteColor];
        label1.textAlignment = NSTextAlignmentCenter;
        label1.font = [UIFont systemFontOfSize:14];
        label1.frame = CGRectMake(nickLabel.right + 5, iconImgView.top, 40, 20);
        label1.center = nickLabel.center;
        label1.left = nickLabel.right +5;
        [basalView addSubview:label1];
        
        UserModel *user = [CommonCache getUserInfo];
        if (([user.uid intValue] == [_layout.model.author_id intValue])||(([user.fid intValue] == [_fid intValue])&&([user.allowdelpost intValue] == 1))) {
            _deButton.hidden = NO;
        }
        if (([user.fid intValue] == [_fid intValue]) && ([user.allowstickthread intValue] == 1)) {
            _dingButton.hidden = NO;
            _digestButton.hidden = NO;
        }
        if (([user.fid intValue] == 0) && ([user.allowstickthread intValue] == 1)) {
            _dingButton.hidden = NO;
            _digestButton.hidden = NO;
            _deButton.hidden = NO;
        }
    }
//    } else {
//        // "评论"标题
//        UILabel *titleLabel = [[UILabel alloc] init];
//        titleLabel.frame = CGRectMake(10, 0, 100, 30);
//        titleLabel.font = FONT(15);
//        titleLabel.text = @"评论";
//        titleLabel.textColor = SS_NAVI_BLUE_COLOR;
//        titleLabel.textAlignment = NSTextAlignmentLeft;
//        [basalView addSubview:titleLabel];
//    }
    return basalView;
}
// 分割线距离左边距离
-(void)viewDidLayoutSubviews
{
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}


#pragma mark - 表情点击代理事件
- (void)faceViewDidChooseFace:(NSString *)face {
    
    UITextField *tf = (UITextField *)[_sendView viewWithTag:kTfTag];
    [tf setText:[NSString stringWithFormat:@"%@%@", tf.text, face]];
}
//点赞
- (void)favourButtonDid:(UIButton *)button{
    UserModel *user = [CommonCache getUserInfo];
    if (user == nil) {
        [self toLogin];
    }else{
        if (_islove == 1) {
            [SVProgressHUD showOnlyStatus:@"您已经点过赞" withDuration:1.5];
        }else{
            [BoyeHttpClient post:@"BY_ForumThread_like" apiVerson:101 params:@{@"tid":_layout.model.tid,@"uid":user.uid} success:^(AFHTTPRequestOperation *operation, id result) {
                [SVProgressHUD showSuccessWithStatus:@"点赞成功" withDuration:1];
                [self _initData];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            }];
        }
        
    }
    
}
//显示更多回复
- (void)toShowMoreRe:(NSInteger)tag{
    ReplyDetailVC *vc = [[ReplyDetailVC alloc] init];
    vc.pid = [NSString stringWithFormat:@"%ld",(long)tag];
    vc.tid = _tid;
    vc.auId = _layout.model.author_id;
    [self.navigationController pushViewController:vc animated:YES];
}
//回复
- (void)replyButtonDid:(UIButton *)button{
    _pid = [NSString stringWithFormat:@"%ld",(long)button.tag];
    [UIView animateWithDuration:0.25 animations:^{
        [_tf becomeFirstResponder];
        _tf.frame = CGRectMake(_imgView.right + 5, 0, SCREEN_WIDTH - 95, 30);
        _tf.center = CGPointMake(_tf.center.x, _sendView.height / 2);
        _reSendButton.hidden = NO;
        _sendButton.hidden = YES;
    }];

}
//删除评论
- (void)deleComment:(UIButton *)button{
    __weak PostDetailVC * that = self;
    _pid = [NSString stringWithFormat:@"%ld",(long)button.tag];
    UserModel *user = [CommonCache getUserInfo];
    NSDictionary *params = @{@"fid":_fid,@"tid":_tid,@"uid":user.uid,@"pid":_pid};
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定删除评论吗" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [BoyeHttpClient post:@"BY_ForumPost_Delete" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
                [SVProgressHUD showSuccessWithStatus:@"删除成功" withDuration:1];
                [that _initData];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"%@",error);
                [SVProgressHUD showErrorWithStatus:@"删除失败，请重试" withDuration:1];
            }];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        [BoyeHttpClient post:@"BY_ForumPost_Delete" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
            [that _initData];
            [SVProgressHUD showSuccessWithStatus:@"删除成功" withDuration:1];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:@"删除失败，请重试" withDuration:1];
        }];
        
    }

   
}

#pragma mark - 点击事件
- (void)_share:(UIButton *)button {
    [self showShareView];
//    NSString *shareText = _layout.model.subject; // 要分享的文字
//    NSString *url = [NSString stringWithFormat:@"%@/%@?type=product&id=%@", WEB_BASE_URL, @"User/download",_tid]; // 要分享的网址
//    // 微信处理
//    [UMSocialWechatHandler setWXAppId:APPKEY_WEIXIN appSecret:APPSECRET_WEIXIN url:url];
//    [UMSocialQQHandler setQQWithAppId:APPID_QQ appKey:APPKEY_QQ url:url];
//    
//
//    // 微博分享的处理
//    [UMSocialData defaultData].extConfig.sinaData.shareText = shareText;
//    [UMSocialData defaultData].extConfig.sinaData.urlResource.url = url;
//    [UMSocialData defaultData].extConfig.sinaData.urlResource.resourceType = UMSocialUrlResourceTypeImage;
//    
//    // 微信消息类型
//    [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
//    
//    // 微信朋友圈分享
//    [UMSocialData defaultData].extConfig.wechatTimelineData.title = shareText;
//    [UMSocialData defaultData].extConfig.wechatTimelineData.url = url;
//    
//    // 微信好友分享
//    [UMSocialData defaultData].extConfig.wechatSessionData.title = shareText;
//    [UMSocialData defaultData].extConfig.wechatSessionData.url = url;
//    
//    // qq分享
//    [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
//    [UMSocialData defaultData].extConfig.qqData.title = shareText;
//    [UMSocialData defaultData].extConfig.qzoneData.title = shareText;
//    [UMSocialData defaultData].extConfig.qqData.url = url;
//    [UMSocialData defaultData].extConfig.qzoneData.url = url;
//    
//    // 实现分享
//    [UMSocialSnsService presentSnsIconSheetView:self
//                                         appKey:APPKEY_UMENG_SOCIAL
//                                      shareText:_layout.model.postContent
//                                     shareImage:DEFAULTSHARE_IMAGE
//                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToQQ,UMShareToWechatSession,UMShareToWechatTimeline,nil]
//                                       delegate:self];
//    
    
    // 使用自定义分享列表面板，则在对应的（微信，qq，微博等）分享按钮中实现下面的方法
    //    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession]
    //                                                       content:@"分享内嵌文字"
    //                                                         image:nil
    //                                                      location:nil
    //                                                   urlResource:nil
    //                                           presentedController:self
    //                                                    completion:^(UMSocialResponseEntity *response) {
    //        if (response.responseCode == UMSResponseCodeSuccess) {
    //            NSLog(@"分享成功！");
    //        }
    //    }];
}
- (UIView *)shareView {
    
    if (_shareView == nil) {
        _shareView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _shareView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        _shareView.alpha = 0;
        _shareView.hidden = YES;
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:_shareView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideShareView)];
        [_shareView addGestureRecognizer:tap];
        
        UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _shareView.width, 80)];
        contentView.backgroundColor = [UIColor whiteColor];
        [_shareView addSubview:contentView];
        contentView.top = _shareView.height;
        contentView.tag = 1000;
        
        NSArray *titles = @[@"QQ", @"微信", @"朋友圈"];
        NSArray *images = @[@"QQ", @"微信", @"朋友圈"];
        for (int i = 0; i < titles.count; i ++) {
            CGFloat x, y = 0, width = SCREEN_WIDTH / titles.count, height = contentView.height;
            x = i * width;
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(x, y, width, height);
            button.backgroundColor = [UIColor clearColor];
            [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
            [button setImage:[UIImage imageNamed:images[i]] forState:UIControlStateNormal];
            [button setImageEdgeInsets:UIEdgeInsetsMake(10, (button.width / 2 - 20), 30, (button.width / 2 - 20))];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = 2000 + i;
            [contentView addSubview:button];
            
            x = 0;
            y = 0;
            width = button.width;
            height = 20;
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
            label.font = FONT(12);
            label.text = titles[i];
            label.textColor = [UIColor darkGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [button addSubview:label];
            label.bottom = button.height - 10;
        }
        
    }
    
    return _shareView;
}
- (void)showShareView {
    self.shareView.hidden = NO;
    
    UIView *contentView = [self.shareView viewWithTag:1000];
    [UIView animateWithDuration:0.3 animations:^{
        _shareView.alpha = 1;
        contentView.bottom = self.shareView.height;
    }];
}
- (void)hideShareView {
    UIView *contentView = [self.shareView viewWithTag:1000];
    [UIView animateWithDuration:0.3 animations:^{
        self.shareView.alpha = 0;
        contentView.top = self.shareView.height;
    } completion:^(BOOL finished) {
        self.shareView.hidden = YES;
    }];
}
- (void)shareBtnAction:(UIButton *)button {
    
    [self hideShareView];
    NSString *shareText = _layout.model.subject; // 要分享的文字
    NSString *url = [NSString stringWithFormat:@"%@/%@?type=thread&id=%@", WEB_BASE_URL, @"User/download",_tid]; // 要分享的网址
//    NSString *shareText = @"森森分享"; // 要分享的文字
//    NSString *url = [NSString stringWithFormat:@"%@/%@?type=product&id=%@", WEB_BASE_URL, @"User/download", _model.p_id]; // 要分享的网址
    
    // 微信处理
    [UMSocialWechatHandler setWXAppId:APPKEY_WEIXIN appSecret:APPSECRET_WEIXIN url:url];
    [UMSocialQQHandler setQQWithAppId:APPID_QQ appKey:APPKEY_QQ url:url];
    // TODO: 分享链接的问题®
    // 微博分享的处理
    [UMSocialData defaultData].extConfig.sinaData.shareText = shareText;
    [UMSocialData defaultData].extConfig.sinaData.urlResource.url = url;
    [UMSocialData defaultData].extConfig.sinaData.urlResource.resourceType = UMSocialUrlResourceTypeImage;
    
    // 微信消息类型
    [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
    
    // 微信朋友圈分享
    [UMSocialData defaultData].extConfig.wechatTimelineData.title = shareText;
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = url;
    
    // 微信好友分享
    [UMSocialData defaultData].extConfig.wechatSessionData.title = shareText;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = url;
    
    // qq分享
    [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
    [UMSocialData defaultData].extConfig.qqData.title = shareText;
    [UMSocialData defaultData].extConfig.qzoneData.title = shareText;
    [UMSocialData defaultData].extConfig.qqData.url = url;
    [UMSocialData defaultData].extConfig.qzoneData.url = url;
    
//    UIImageView * imageView  = [[UIImageView alloc] init];
//    NSArray *array =  _layout.model.imgAry;
//    NSString *urlStr;
//    if (array.count == 0) {
//        urlStr = nil;
//    }else{
//        urlStr = array[0];
//    }
    
    switch (button.tag) {
        case 2000:
        {
//            [imageView setImageURLStr:urlStr placeholder:DEFAULT_IMAGE];
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQQ]
                                                               content:_layout.model.postContent
                                                                 image:_mainImage//[UIImage getImageFromURL:self.model.main_img]
                                                              location:nil
                                                           urlResource:nil
                                                   presentedController:self
                                                            completion:^(UMSocialResponseEntity *response) {
                                                                if (response.responseCode == UMSResponseCodeSuccess) {
                                                                    NSLog(@"分享成功！");
                                                                }
                                                            }];
        }
            break;
        case 2001:
        {
//            [imageView setImageURLStr:urlStr placeholder:DEFAULT_IMAGE];
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession]
                                                               content:_layout.model.postContent
                                                                 image:_mainImage
                                                              location:nil
                                                           urlResource:nil
                                                   presentedController:self
                                                            completion:^(UMSocialResponseEntity *response) {
                                                                if (response.responseCode == UMSResponseCodeSuccess) {
                                                                    NSLog(@"分享成功！");
                                                                }
                                                            }];
        }
            break;
        case 2002:
        {
//            [imageView setImageURLStr:urlStr placeholder:DEFAULT_IMAGE];
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatTimeline]
                                                               content:_layout.model.postContent
                                                                 image:_mainImage
                                                              location:nil
                                                           urlResource:nil
                                                   presentedController:self
                                                            completion:^(UMSocialResponseEntity *response) {
                                                                if (response.responseCode == UMSResponseCodeSuccess) {
                                                                    NSLog(@"分享成功！");
                                                                }
                                                            }];
        }
            break;
            
        default:
            break;
    }
}


// 分享回调代理
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}

//举报
- (void)_report:(UIButton *)button {
   
    UserModel *user = [CommonCache getUserInfo];
    if (user == nil) {
       [self toLogin];
    }else{
    NSDictionary *params = @{@"fid":_fid,@"tid":_tid,@"uid":_layout.model.author_id,@"op_uid":user.uid,@"pid":_layout.model.pid,@"username":_layout.model.author};
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定举报帖子吗" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"举报" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [BoyeHttpClient post:@"BY_CoreReport_bbsReport" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {

                [SVProgressHUD showSuccessWithStatus:@"举报成功" withDuration:1];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"%@",error);
                [SVProgressHUD showErrorWithStatus:@"举报失败，请重试" withDuration:1];
            }];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        [BoyeHttpClient post:@"BY_ForumThread_delete" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
            [SVProgressHUD showSuccessWithStatus:@"举报成功" withDuration:1];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:@"举报失败，请重试" withDuration:1];
        }];
    }
    }
}
// 导航栏右侧按钮收藏
- (void)_naviRightAction:(UIButton *)button {
    UserModel *user =  [CommonCache getUserInfo];
    if (user == nil) {
        [self toLogin];
    }else{
        if (_isLike == YES)
        {
           [BoyeHttpClient post:@"BY_ForumThread_favorites" apiVerson:100 params:@{@"uid":user.uid,@"tid":_layout.model.tid ,@"favorite_value" :@"0"} success:^(AFHTTPRequestOperation *operation, id result) {
               [SVProgressHUD showSuccessWithStatus:@"取消收藏成功" withDuration:1];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
               [SVProgressHUD showErrorWithStatus:@"取消收藏失败" withDuration:1];
            }];
            [button setImage:[UIImage imageNamed:@"论坛首页_详情页_收藏"] forState:UIControlStateNormal];
        }else{
            [BoyeHttpClient post:@"BY_ForumThread_favorites" apiVerson:100 params:@{@"uid":user.uid,@"tid":_layout.model.tid ,@"favorite_value" :@"1"} success:^(AFHTTPRequestOperation *operation, id result) {
               [SVProgressHUD showSuccessWithStatus:@"收藏成功" withDuration:1];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [SVProgressHUD showErrorWithStatus:@"收藏失败" withDuration:1];
            }];
            [button setImage:[UIImage imageNamed:@"论坛首页_详情页_收藏2"] forState:UIControlStateNormal];
            }
            _isLike = !_isLike;
    }
}
// 发送评论
- (void)_sendAction:(UIButton *)button {
     UserModel *user =  [CommonCache getUserInfo];
    if (user == nil) {
        [self toLogin];
    }else{
        if (([user.allowpost integerValue] == 0) && (([user.fid integerValue] == [_fid integerValue])||([user.fid integerValue] == 0))) {
            [SVProgressHUD showErrorWithStatus:@"您已经被禁言，暂时无法发言" withDuration:1.5];
            return;
        }else{
            if (_tf.text.length == 0) {
                [SVProgressHUD showErrorWithStatus:@"请填写完整" withDuration:1.5];
                return;
            }else{
                [SVProgressHUD showWithStatus:@"评论中,请稍等"];
                self.view.userInteractionEnabled = NO;
                NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
                [params setObject:_layout.model.tid forKey:@"tid"];
                [params setObject:_layout.model.fid forKey:@"fid"];
                [params setObject:user.nickname forKey:@"author"];
                [params setObject:user.uid forKey:@"author_id"];
                [params setObject:_tf.text forKey:@"message"];
                if (_imIdAry.count != 0) {
                    NSString *attid = @"";
                    for (NSString *imId in _imIdAry) {
                        attid = [attid stringByAppendingString:[NSString stringWithFormat:@"%@,",imId]];
                    }
                    NSString *attids = [attid substringToIndex:attid.length - 1];
                    [params setObject:attids forKey:@"attachments"];
                }
                __weak PostDetailVC * that = self;
                [BoyeHttpClient post:@"BY_ForumPost_reply" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
                    self.view.userInteractionEnabled = YES;
                    [that _initData];
                    [SVProgressHUD dismiss];
                    [SVProgressHUD showSuccessWithStatus:@"评论成功" withDuration:1];
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    self.view.userInteractionEnabled = YES;
                    [SVProgressHUD dismiss];
                    [SVProgressHUD showErrorWithStatus:error.domain withDuration:1];
                }];
            }
        }
    }
    [self keyboardDown];
    _tf.text = nil;
    [_tf resignFirstResponder];
    [_imgAry removeAllObjects];
    [_imIdAry removeAllObjects];
    [_collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    _notesLabel.text = [NSString stringWithFormat:@"已选%li张，还剩%li张可选，多余三张可滑动查看", (unsigned long)_imgAry.count,6 - _imgAry.count];
}
// 点击表情
- (void)_faceViewTap:(UITapGestureRecognizer *)tap {
    
    [_faceView show];
    
    _contentBasalView.top = _faceView.bottom;
}
//添加图片
- (void)_imageAdd:(UITapGestureRecognizer *)tap {
    
    [_faceView hide];
    
    [UIView animateWithDuration:0.25 animations:^{
        _contentBasalView.bottom = SCREEN_HEIGHT - 64;
        _sendView.bottom = _contentBasalView.top;
    }];
    
}
//回复按钮
- (void)_replyAction:(UIButton *)button {
    UserModel *user =  [CommonCache getUserInfo];
    if (user == nil) {
        [self toLogin];
    }else{
        if (([user.allowpost integerValue] == 0) && (([user.fid integerValue] == [_fid integerValue])||([user.fid integerValue] == 0))) {
            [SVProgressHUD showErrorWithStatus:@"您已经被禁言，暂时无法发言" withDuration:1.5];
            return;
        }else{
            if (_tf.text.length == 0) {
                [SVProgressHUD showErrorWithStatus:@"请填写完整" withDuration:1];
                return;
            }else{
                [SVProgressHUD showWithStatus:@"回复中,请等待"];
                self.view.userInteractionEnabled = NO;
                [BoyeHttpClient post:@"BY_ForumPost_replyPost" apiVerson:100 params:@{@"tid":_layout.model.tid,@"pid":_pid,@"author":user.nickname,@"author_id":user.uid,@"comment":_tf.text} success:^(AFHTTPRequestOperation *operation, id result) {
                    self.view.userInteractionEnabled = YES;
                    [self _initData];
                    [SVProgressHUD showSuccessWithStatus:@"回复成功" withDuration:1];
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    self.view.userInteractionEnabled = YES;
                    [SVProgressHUD showErrorWithStatus:error.domain withDuration:1];
                }];
            }
        }
    }
    [self keyboardDown];
    _tf.text = nil;
    [_tf resignFirstResponder];
}

 //删除帖子按钮
 - (void)deletePost:(UIButton *)button{
 
 
     if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
 
         UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定删除帖子吗" message:nil preferredStyle:UIAlertControllerStyleAlert];
         UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
         UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
             UserModel *user = [CommonCache getUserInfo];
             [SVProgressHUD showWithStatus:@"删除ing，请等待"];
             self.view.userInteractionEnabled = NO;
             [BoyeHttpClient post:@"BY_ForumThread_delete" apiVerson:100 params:@{@"tid":_layout.model.tid,@"uid":user.uid} success:^(AFHTTPRequestOperation *operation, id result) {
                 self.view.userInteractionEnabled = YES;
                 [SVProgressHUD dismiss];
                 [self.navigationController popViewControllerAnimated:YES];
                 [SVProgressHUD showSuccessWithStatus:@"删除成功" withDuration:1];
             } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                 self.view.userInteractionEnabled = YES;
                 [SVProgressHUD dismiss];
                 [SVProgressHUD showErrorWithStatus:@"删除失败，请重试" withDuration:1];
             }];
         }];
         [alertController addAction:cancelAction];
         [alertController addAction:okAction];
         [self presentViewController:alertController animated:YES completion:nil];
 
     }else{
         UserModel *user = [CommonCache getUserInfo];
         [SVProgressHUD showWithStatus:@"删除ing，请等待"];
         self.view.userInteractionEnabled = NO;
         [BoyeHttpClient post:@"BY_ForumThread_delete" apiVerson:100 params:@{@"tid":_layout.model.tid,@"uid":user.uid} success:^(AFHTTPRequestOperation *operation, id result) {
             [SVProgressHUD dismiss];
             [self.navigationController popViewControllerAnimated:YES];
             [SVProgressHUD showSuccessWithStatus:@"删除成功" withDuration:1];
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             self.view.userInteractionEnabled = YES;
             [SVProgressHUD dismiss];
             [SVProgressHUD showErrorWithStatus:@"删除失败，请重试" withDuration:1];
         }];
 
     }
 }
 //置顶帖子按钮
 - (void)dingPost:(UIButton *)button{
     _isStick = !_isStick;
     NSString *stick = [NSString stringWithFormat:@"%d",_isStick];
     NSString *title;
     NSString *but1;
     if (_isStick == 1) {
         title = @"确定置顶帖子吗";
         but1 = @"置顶" ;
     }else{
         title = @"确定取消置顶帖子吗";
         but1 = @"取消置顶" ;
     }
 
     if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
 
         UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
         UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
             _isStick = !_isStick;
         }];
         UIAlertAction *okAction = [UIAlertAction actionWithTitle:but1 style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
             UserModel *user = [CommonCache getUserInfo];
             [BoyeHttpClient post:@"BY_ForumThread_stick" apiVerson:100 params:@{@"tid":_layout.model.tid,@"uid":user.uid,@"stick_value":stick} success:^(AFHTTPRequestOperation *operation, id result) {
                 if (_isStick == 1) {
                     [SVProgressHUD showSuccessWithStatus:@"置顶成功" withDuration:1];
                 }else{
                     [SVProgressHUD showSuccessWithStatus:@"取消置顶成功" withDuration:1];
                 }
             } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                 NSLog(@"%@",error);
                 if (_isStick == 1) {
                     [SVProgressHUD showErrorWithStatus:@"置顶失败，请重试" withDuration:1];
                 }else{
                     [SVProgressHUD showErrorWithStatus:@"取消置顶失败，请重试" withDuration:1];
                 }
                 _isStick = !_isStick;
             }];
         }];
         [alertController addAction:cancelAction];
         [alertController addAction:okAction];
         [self presentViewController:alertController animated:YES completion:nil];
 
     }else{
         UserModel *user = [CommonCache getUserInfo];
         [BoyeHttpClient post:@"BY_ForumThread_stick" apiVerson:100 params:@{@"tid":_layout.model.tid,@"uid":user.uid,@"stick_value":stick} success:^(AFHTTPRequestOperation *operation, id result) {
             if (_isStick == 1) {
                 [SVProgressHUD showSuccessWithStatus:@"置顶成功" withDuration:1];
             }else{
                 [SVProgressHUD showSuccessWithStatus:@"取消置顶成功" withDuration:1];
             }
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             if (_isStick == 1) {
                 [SVProgressHUD showErrorWithStatus:@"置顶失败，请重试" withDuration:1];
             }else{
                 [SVProgressHUD showErrorWithStatus:@"取消置顶失败，请重试" withDuration:1];
             }
 
         }];
 
     }
 
}


//加精
- (void)_digest:(UIButton *)button {
    _isDigest = !_isDigest;
    NSString *digest = [NSString stringWithFormat:@"%d",_isDigest];
    NSString *title;
    NSString *but1;
    if (_isDigest == 1) {
        title = @"确定设置精华帖吗";
        but1 = @"加精" ;
    }else{
        title = @"确定取消精华帖吗";
        but1 = @"取消加精" ;
    }
    
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            _isDigest = !_isDigest;
        }];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:but1 style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UserModel *user = [CommonCache getUserInfo];
            [BoyeHttpClient post:@"BY_ForumThread_digest" apiVerson:100 params:@{@"tid":_layout.model.tid,@"uid":user.uid,@"digest_value":digest} success:^(AFHTTPRequestOperation *operation, id result) {
                if (_isDigest == 1) {
                    [SVProgressHUD showSuccessWithStatus:@"加精成功" withDuration:1];
                }else{
                    [SVProgressHUD showSuccessWithStatus:@"取消加精成功" withDuration:1];
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                if (_isDigest == 1) {
                    [SVProgressHUD showErrorWithStatus:@"加精失败，请重试" withDuration:1];
                }else{
                    [SVProgressHUD showErrorWithStatus:@"取消加精失败，请重试" withDuration:1];
                }
                
            }];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        UserModel *user = [CommonCache getUserInfo];
        [BoyeHttpClient post:@"BY_ForumThread_digest" apiVerson:100 params:@{@"tid":_layout.model.tid,@"uid":user.uid,@"digest_value":digest} success:^(AFHTTPRequestOperation *operation, id result) {
            if (_isDigest == 1) {
                [SVProgressHUD showSuccessWithStatus:@"加精成功" withDuration:1];
            }else{
                [SVProgressHUD showSuccessWithStatus:@"取消加精成功" withDuration:1];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            if (_isDigest == 1) {
                [SVProgressHUD showErrorWithStatus:@"加精失败，请重试" withDuration:1];
            }else{
                [SVProgressHUD showErrorWithStatus:@"取消加精失败，请重试" withDuration:1];
            }
            
        }];
        
    }

}

#pragma mark - 键盘弹出事件
- (void)keyboardFrameChange:(NSNotification *)notification {

    [UIView animateWithDuration:0.25 animations:^{
        // 获取键盘的frame
        NSValue *boundsValue = [notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect frame = [boundsValue CGRectValue];
        // 键盘y值，是对于手机屏幕的，所以没上升的时候是屏幕高度
        CGFloat y = frame.origin.y;
        
        if (y < SCREEN_HEIGHT) {
            _sendView.bottom = y - 64;
            _maskView.bottom = _sendView.top;
            _maskView.hidden = NO;
        }
        // 键盘下降
        else {
            _sendView.bottom = y - 64;
            _maskView.bottom = _sendView.top;
            _maskView.hidden = YES;
        }
    
    }];
}
// 表情视图位置改变方法
- (void)faceViewFrameChange:(NSNotification *)notification {
    
    [_APP_KEYWINDOW endEditing:YES]; // 隐藏键盘
    
    [UIView animateWithDuration:0.25 animations:^{
        NSDictionary *info = notification.userInfo;
        NSString *frameStr = info[FaceViewFrameEndInfo];
        CGRect frame = CGRectFromString(frameStr);
        // 键盘上升
        if (frame.origin.y < SCREEN_HEIGHT - 64) {
            _sendView.bottom = frame.origin.y;
            _maskView.bottom = _sendView.top;
            _maskView.hidden = NO;
        }
        // 键盘下降
        else {
            _sendView.bottom = frame.origin.y;
            _maskView.bottom = _sendView.top;
            _maskView.hidden = YES;
        }
    }];
}
// 重写键盘下降事件（外加一个隐藏表情）
- (void)keyboardDown {
    [super keyboardDown];
    
    [UIView animateWithDuration:0.25 animations:^{
        _contentBasalView.top = SCREEN_HEIGHT - 64;
    }];
    [_faceView hide];
    _tf.frame = CGRectMake(65, 0, SCREEN_WIDTH - 125, 30);
    _tf.center = CGPointMake(_tf.center.x, _sendView.height / 2);
    _reSendButton.hidden = YES;
    _sendButton.hidden = NO;
}


#pragma mark - 添加图片
// 创建放置图片的滑动视图
- (void)_createCollectionView {
    
    // 初始化数据数组
    if (_imgAry == nil) {
        _imgAry = [[NSMutableArray alloc] init];
    } else {
        [_imgAry removeAllObjects];
    }
    if (_imIdAry == nil) {
        _imIdAry = [[NSMutableArray alloc] init];
    } else {
        [_imIdAry removeAllObjects];
    }
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat width = (SCREEN_WIDTH - 15 * 4) / 3;
    CGFloat height = width;
    layout.itemSize = CGSizeMake(width, height);
    layout.minimumInteritemSpacing = 15;
    layout.minimumLineSpacing = 15;
    layout.sectionInset = UIEdgeInsetsMake(0, 15, 0, 15);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    _contentBasalView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 64, SCREEN_WIDTH, height + 40)];
    _contentBasalView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
 
    [self.view addSubview:_contentBasalView];
    
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 5 , SCREEN_WIDTH, height) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_contentBasalView addSubview:_collectionView];
    // 注册单元格
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"imgCell"];
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"btnCell"];
    
    // 标注视图，注释当前已经有几张图片，并告知还有几张可选
    CGFloat x = 0;
    CGFloat y = _collectionView.bottom + 10;
    CGFloat labWidth = SCREEN_WIDTH;
    CGFloat labHeight = 20;
    _notesLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, labWidth, labHeight)];
    _notesLabel.font = FONT(15);
    _notesLabel.text = @"已选0张，还剩6张可选，多余三张可滑动查看";
    _notesLabel.textColor = [UIColor colorWithWhite:0.5 alpha:1];
    _notesLabel.textAlignment = NSTextAlignmentCenter;
    [_contentBasalView addSubview:_notesLabel];
    
}



#pragma mark - UICollectionView 代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _imgAry.count + 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat width, height;
    CGFloat margin = 15;
    width = (SCREEN_WIDTH - margin * 4) / 3;
    height = width;
    
    // 按钮单元格（添加图片）
    if (indexPath.row == _imgAry.count) {
        UICollectionViewCell *btnCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"btnCell" forIndexPath:indexPath];
        // 添加按钮
        UIButton *addbutton = [UIButton buttonWithType:UIButtonTypeCustom];
        addbutton.frame = CGRectMake(0, 0, width, height);
        [addbutton setImage:[UIImage imageNamed:@"论坛_添加图片"] forState:UIControlStateNormal];
        [addbutton addTarget:self action:@selector(_pictureTap:) forControlEvents:UIControlEventTouchUpInside];
        addbutton.layer.borderColor = ([UIColor colorWithRGBHex:0xbbbbbb]).CGColor;
        addbutton.layer.borderWidth = 0.5;
        [btnCell addSubview:addbutton];
        
        return btnCell;
    }
    // 图片单元格
    else {
        UICollectionViewCell *imgCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imgCell" forIndexPath:indexPath];
        if (imgCell == nil) {
            imgCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imgCell" forIndexPath:indexPath];
        }
        else
        {
            //删除cell的所有子视图
            while ([imgCell.subviews lastObject] != nil)
            {
                [(UIView*)[imgCell.subviews lastObject] removeFromSuperview];
            }
        }
        UIImageView *imgView = [[UIImageView alloc] init];
        imgView.userInteractionEnabled = YES;
        imgView.frame = CGRectMake(0, 0, width, height);
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imgView.image = _imgAry[indexPath.row];
        [imgCell addSubview:imgView];
        
        // 删除按钮
        UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        deleteBtn.frame = CGRectMake(0, 0, 20, 20);
        [deleteBtn setBackgroundImage:[UIImage imageNamed:@"论坛_删除图片"] forState:UIControlStateNormal];
        [deleteBtn addTarget:self action:@selector(_deleteImgAction:) forControlEvents:UIControlEventTouchUpInside];
        [imgView addSubview:deleteBtn];
        deleteBtn.center = CGPointMake(imgView.width - 15, 15);
        return imgCell;
    }
    
}

// 删除图片
- (void)_deleteImgAction:(UIButton *)button {
    // 找到对应的单元格来获得数组中图片的索引，然后删除图片，重载UICollectionView
    UIImageView *imgView = (UIImageView *)button.superview;
    UICollectionViewCell *imgCell = (UICollectionViewCell *)imgView.superview;
    NSIndexPath *indexPath = [_collectionView indexPathForCell:imgCell];
    if (button == nil) {
        [_imgAry removeLastObject];
    }else{
        [_imgAry removeObjectAtIndex:indexPath.row];
    }
    [_collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    if ((_imIdAry.count != indexPath.row) && button != nil){
        // 删除图片id
        [_imIdAry removeObjectAtIndex:indexPath.row];
    }
    // 刷新注释文本
    _notesLabel.text = [NSString stringWithFormat:@"已选%li张，还剩%li张可选，多余三张可滑动查看", (unsigned long)_imgAry.count,6 - _imgAry.count];
}
// 添加图片
- (void)_addImgAction:(UIImage *)image {
    
    if (_imgAry.count == 6) {
        [SVProgressHUD showErrorWithStatus:@"您最多可上传6张图片" withDuration:2];
        return;
    } else {
        [_imgAry addObject:image];
        [_collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
        // 刷新注释文本
        _notesLabel.text = [NSString stringWithFormat:@"已选%li张，还剩%li张可选，多余三张可滑动查看", (unsigned long)_imgAry.count,6 - _imgAry.count];
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_imgAry.count inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
}
// 图片
- (void)_pictureTap:(UIButton *)button {
    UserModel *user = [CommonCache getUserInfo];
    if (user != nil) {
        
        if (_imgAry.count == 6) {
            [SVProgressHUD showErrorWithStatus:@"您最多可上传6张图片" withDuration:2];
            return;
        }
        // 适配版本iOS8.0以上
        if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
            // 创建ActionSheet
            NSString *albumButtonTitle = @"从相册中选择";
            NSString *cameraButtonTitle = @"拍照";
            NSString *cancelButtonTitle = @"取消";
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            // 添加点击动作
            // 取消
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:nil];
            // 相册中
            UIAlertAction *albumAction = [UIAlertAction actionWithTitle:albumButtonTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                
                [self _choosePhotoFromAlbum];
            }];
            // 拍照
            UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:cameraButtonTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                
                [self _getphotoFromCamera];
            }];
            
            // Add the actions.
            [alertController addAction:cancelAction];
            [alertController addAction:albumAction];
            [alertController addAction:cameraAction];
            
            [self presentViewController:alertController animated:YES completion:nil];
        }
        // 适配版本8.0以下
        else {
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册中选择",@"拍照", nil];
            [sheet showInView:self.view];
        }
    }else{
        [self toLogin];
    }
    
}
#pragma mark - 头像图片选择相关操作
// 从相册中选择照片
- (void)_choosePhotoFromAlbum
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        [SVProgressHUD showErrorWithStatus:@"相册不可用！" withDuration:1];
        return;
    }
    [self _changeToPickerController:sourceType];
}

// 通过拍照获取照片
- (void)_getphotoFromCamera
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        [SVProgressHUD showErrorWithStatus:@"相机不可用！" withDuration:1];
        return;
    }
    [self _changeToPickerController:sourceType];
}

// 创建并跳转到图片获取界面
- (void)_changeToPickerController:(UIImagePickerControllerSourceType)sourceType
{
    //创建图片拾取界面
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    //设置可编辑
    pickerController.sourceType = sourceType;
    if (pickerController.sourceType == UIImagePickerControllerSourceTypeCamera) {
        pickerController.allowsEditing = YES;
    }
    pickerController.title = @"图片选择";
    [pickerController.navigationBar setTintColor:[UIColor darkGrayColor]];
    [self presentViewController:pickerController animated:YES completion:nil];
}

//UIImagePickerController代理方法，选取图片之后处理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *showImage;
    UIImage *editedImage = (UIImage *)[info objectForKey:UIImagePickerControllerEditedImage];
    UIImage *originalImage = (UIImage *)[info objectForKey:UIImagePickerControllerOriginalImage];
    
    if (editedImage) {
        // 保存到相册
        UIImageWriteToSavedPhotosAlbum(editedImage, nil, nil, nil);
        // 设置图片
        showImage = editedImage; // 相册图片可截取，一直是正方形的
        originalImage = editedImage;
    }
    else if (originalImage) {
        // 设置图片
        showImage = [originalImage getCenterImage];
    }
    // 图片添加
    [self _addImgAction:showImage];
    
    NSData *imageData = UIImageJPEGRepresentation(originalImage, 1);
    CGFloat length_kb = [imageData length] / 4096.0;
    // 压缩文件

    if (length_kb >= 500 ) {
        //        NSLog(@"=====%lf",length_kb);
        originalImage = [UIImage imageWithData:UIImageJPEGRepresentation(originalImage, 0)];
        imageData = UIImageJPEGRepresentation(originalImage, 1);
        length_kb = [imageData length] / 4096.0;
    }
    if (length_kb >= 500) {
        originalImage = [self scaleToSize:CGSizeMake(500, 500) :originalImage];
    }

    [self dismissViewControllerAnimated:YES completion:^{
        self.view.userInteractionEnabled = NO;
        //上传图片
        [BoyeHttpClient uploadImage:originalImage type:@"bbs" success:^(NSDictionary *dataDic) {
            NSString *imageId  =  dataDic[@"id"];
            [_imIdAry addObject:imageId];
            self.view.userInteractionEnabled = YES;
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self _deleteImgAction:nil];
            self.view.userInteractionEnabled = YES;
        }];
    }];
    
}



#pragma mark - UIActionSheet代理方法（适配iOS8.0以下时使用）
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    // 选择照片
    // 从相册中选择
    if (buttonIndex == 0) {
        [self _choosePhotoFromAlbum];
    }
    // 通过拍照获取
    else if (buttonIndex == 1) {
        [self _getphotoFromCamera];
    }
}

//裁剪图片
-(UIImage*)scaleToSize:(CGSize)size :(UIImage *)image
{
    CGFloat width = CGImageGetWidth(image.CGImage);
    CGFloat height = CGImageGetHeight(image.CGImage);
    
    float verticalRadio = size.height*1.0/height;
    float horizontalRadio = size.width*1.0/width;
    
    float radio = 1;
    if(verticalRadio > 1 && horizontalRadio > 1)
    {
        radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio;
    }
    else
    {
        radio = verticalRadio > horizontalRadio ? verticalRadio : horizontalRadio;
    }
    
    width = width*radio;
    height = height*radio;
    
    int xPos = (size.width - width)/2;
    int yPos = (size.height-height)/2;
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(xPos, yPos, width, height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}

//去登录
- (void)toLogin{
    LoginVC *vc = [[LoginVC alloc] init];
    BaseNavVC *naviVc = [[BaseNavVC alloc] initWithRootViewController:vc];
    [self presentViewController:naviVc animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
